package com.abc.xxx.config.security;

import com.abc.xxx.util.Result;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest req,
                                        HttpServletResponse res,
                                        AuthenticationException ex) throws IOException, ServletException {
        String desc = translate(ex.getMessage());
        Result json = Result.error("login").msg(desc).data("exception", ex.getMessage());
        res.setStatus(200);
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        res.getWriter().write(json.toString());
    }

    public String translate(String errorMsg){
        if ("Bad credentials".equals(errorMsg)){
            return "用户名或密码有误";
        }
        return "登录失败";
    }

}
